import { Toast } from "antd-mobile";
import axios from "axios";
import { ShowFail, ShowLoading, ShowMessage } from "../utils/message";
import { history } from "../utils";

export const baseURL =  "" //"http://124.93.196.45:10001"
export const imgUrl = 'http://116.62.165.233:3333/'

const request = axios.create({
    baseURL:baseURL,
    timeout:6000,
    headers:{
        
    }
})


// 请求拦截
request.interceptors.request.use((req)=>{
    const AppToken:any = localStorage.getItem("AppToken")
    // req.headers.Authorization = eval(AppToken)   // 设置请求头 设置token

    if(req.url!='https://m.maizuo.com/gateway'){
        // 动态设置token 
        req.headers.Authorization = eval(AppToken);  // 设置请求头 设置token 
    }

    ShowLoading()
    return req
},err=>{
    ShowFail("请求失败")
})


// 响应拦截
request.interceptors.response.use((res)=>{
    console.log(res.data)
    if(res.data.code == "200"){
        Toast.clear()
    }else{
        if(res.data.code=='401'){
            ShowMessage('请先登录')
            // 跳转登录 
            // history.push('/login')   // 路由跳转 页面不刷新 
            // window.location.reload()
            window.location.href = '#/login' 
        }else{
            ShowFail(res.data.msg || "响应失败")
        }
    }
    return res
},err=>{
    console.log(err);
    
    ShowFail("响应失败")
})


// 封装Get / Post
export const Get = (url: string, params?: object, headers?: object) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: "GET",
            params,
            headers,
        })
            .then(res => {
                resolve(res.data)  // res.data 返回的时候不需要 res.data 
            })
            .catch(err => {
                reject(err)
            })
    })
}

export const Post = (url: string, data?: object, params?: object, headers?: object) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: "POST",
            data,
            params,
            headers,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}
export default request